package com.common.tools;

import java.io.File;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Zixiang Hu
 * @description
 * @create 2021-04-16-11:14
 */
public class CommonTool {
    /**
     * 获得本机正在使用的ip地址
     *
     * @return
     */
    public static String getLocalIPList() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("IP地址获取失败" + e.toString());
        }
        return "";
    }

    /**
     * 包扫描函数
     * 获得指定包名下的所有类
     *
     * @param pack 诸如：com.learn.hzx
     * @return 返回全类名的集合
     * @throws IOException
     */
    public static Set<String> getClasses(String pack) throws IOException {
        Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(pack.replace(".", "/"));
        Set<String> classSet = new HashSet<>();
        while (urls.hasMoreElements()) {
            String path = urls.nextElement().getFile().substring(1);
            getFiles(path, pack, classSet);
        }
        return classSet;
    }

    public static void getFiles(String path, String packPath, Set<String> set) {
        File parentFile = new File(path);
        File[] files = parentFile.listFiles();
        String completePath = packPath + ".";
        for (File file : files) {
            if (file.isFile()) {
                set.add(completePath + file.getName().substring(0, file.getName().lastIndexOf(".")));
            } else
                getFiles(file.getPath(), completePath + file.getName(), set);
        }
    }

    /**
     * 测试某个IP的端口是否可以连接成功
     * @param socketAddress
     * @return true代表可以连接成功；false代表不可以连接成功
     * @throws IOException
     */
    public static boolean canConnect(InetSocketAddress socketAddress) throws IOException {
        Socket socket = new Socket();
        try {
            socket.connect(socketAddress, 2000);
        } catch (Exception e) {
            socket.close();
            return false;
        }
        socket.close();
        return true;
    }

}
